/*
 * @Author: liuxiao
 * @Date: 2023-11-27 00:36:45
 * @Last Modified by: liuxiao
 * @Last Modified time: 2023-11-27 23:14:46
 * @ps：服务层，主要控制数据库相关业务逻辑
 */

//const User = require('../model/user.model')
const { edu_users: User } = require('../dbModel/index')

class UserService {
  async createUser(username, password) {
    //todo:写入数据库
    //由于键值，名称一致，可以简写
    const res = await User.create({ username, password })
    console.log(res.dataValues)
    return res.dataValues //这里是一个psomise对象
  }

  //获取用户信息
  async getUserInfo({ id, username, password, is_admin }) {
    const whereOpt = {}

    //短路运算，如果id存在才能执行后续操作，如果不存在，直接跳过
    id && Object.assign(whereOpt, { id })
    username && Object.assign(whereOpt, { username })
    password && Object.assign(whereOpt, { password })
    is_admin && Object.assign(whereOpt, { is_admin })

    const res = await User.findOne({
      attributes: ['id', 'username', 'password', 'is_admin'],
      where: whereOpt
    })

    return res ? res.dataValues : null
  }

  async updateById({ id, username, password, is_admin }) {
    const whereOpt = { id }
    const newUser = {}

    username && Object.assign(newUser, { username })
    password && Object.assign(newUser, { password })
    is_admin && Object.assign(newUser, { is_admin })

    console.log(newUser, 'newUser')
    const res = await User.update(newUser, { where: whereOpt })

    return res[0] > 0 ? true : false
  }

  async testSer() {
    const res = edu_courses.findAll()
    return res
  }
}

module.exports = new UserService()
